from typing import List

from PySide6 import QtWidgets, QtCore
from PySide6.QtWidgets import QApplication, QMessageBox

from mquant.trader.object import RiskManagerModelData, AccountModelData
from mquant_sqlite.sqlite_database import RiskManagerModelTable, SqliteDatabase, AccountModelDataTable


class MRiskQDialog(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()
        self.db = SqliteDatabase()
        self.init_ui()

    def init_ui(self) -> None:
        self.setWindowTitle("交易风控")

        self.table_widget = QtWidgets.QTableWidget()
        self.table_widget.setColumnCount(5)
        self.table_widget.setHorizontalHeaderLabels(["ID", "用户名", "账号", "最大亏损(初始本金百分比)", "是否休眠"])

        self.table_widget.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Stretch)
        self.table_widget.verticalHeader().setVisible(False)
        self.table_widget.setMinimumWidth(800)

        save_button = QtWidgets.QPushButton("保存")

        save_button.clicked.connect(self.save_data)

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.table_widget)
        layout.addWidget(save_button)

        self.setLayout(layout)

        # Set Fix Size
        hint = self.sizeHint()
        self.setFixedSize(int(hint.width() * 1.2), hint.height())
        self.load_data()

    def load_data(self) -> None:
        #  从数据库加载数据，并显示在表格中
        risk_managers: List[RiskManagerModelData] = self.db.load_riskManager_data()
        # 只显示存在的账户
        accounts:List[AccountModelData]=self.db.load_account_data()
        account_account = [account.account for account in accounts]

        self.table_widget.setRowCount(len(account_account))

        for row, risk_manager in enumerate(risk_managers):

            if risk_manager.account not in account_account:
                continue

            item_id = QtWidgets.QTableWidgetItem(str(risk_manager.id))
            item_username = QtWidgets.QTableWidgetItem(risk_manager.username)
            item_account = QtWidgets.QTableWidgetItem(risk_manager.account)
            item_max_loss = QtWidgets.QTableWidgetItem(str(risk_manager.max_loss))
            item_sleep = QtWidgets.QTableWidgetItem(str(risk_manager.sleep))

            self.table_widget.setItem(row, 0, item_id)
            self.set_cell_editable(row, 0, False)
            self.table_widget.setItem(row, 1, item_username)
            self.set_cell_editable(row, 1, False)
            self.table_widget.setItem(row, 2, item_account)
            self.set_cell_editable(row, 2, False)
            self.table_widget.setItem(row, 3, item_max_loss)
            self.set_cell_editable(row, 3, True)
            self.table_widget.setItem(row, 4, item_sleep)
            self.set_cell_editable(row, 4, True)

    def save_data(self) -> None:
        # 保存表格数据到数据库
        row_count = self.table_widget.rowCount()
        risk_managers: List[RiskManagerModelData] = []
        for row in range(row_count):
            id = self.table_widget.item(row, 0).text()
            username = self.table_widget.item(row, 1).text()
            account = self.table_widget.item(row, 2).text()
            max_loss = self.table_widget.item(row, 3).text()
            sleep = self.table_widget.item(row, 4).text()

            # 获取每一行的数据并保存到数据库
            risk_manager: RiskManagerModelData = RiskManagerModelData(
                id=int(id),
                username=username,
                account=account,
                max_loss=float(max_loss),
                sleep=int(sleep)
            )
            risk_managers.append(risk_manager)
        res = self.db.save_riskManager_data(risk_managers)

        if res:
            QMessageBox.information(self, "成功", "保存成功，重启后生效！")
        else:
            QMessageBox.warning(self, "警告", "保存失败")

        # 保存完成后重新加载数据
        self.load_data()

    def set_cell_editable(self, row, column, editable):
        item = self.table_widget.item(row, column)
        if item:
            flags = item.flags()
            if editable:
                flags |= QtCore.Qt.ItemFlag.ItemIsEnabled
            else:
                flags &= ~QtCore.Qt.ItemFlag.ItemIsEnabled
            item.setFlags(flags)

    def closeEvent(self, event):
        # 比如保存数据或执行清理操作
        self.db.quit()
        # 调用父类的 closeEvent 方法，以确保对话框正常关闭
        super().closeEvent(event)


class AccountQDialog(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()
        self.db = SqliteDatabase()
        self.setWindowTitle("账户设置")

        account_layout = QtWidgets.QVBoxLayout()
        button_layout = QtWidgets.QHBoxLayout()

        add_button = QtWidgets.QPushButton("新增账户")
        delete_button = QtWidgets.QPushButton("删除账户")
        save_button = QtWidgets.QPushButton("保存")

        button_layout.addWidget(add_button)
        button_layout.addWidget(delete_button)
        button_layout.addWidget(save_button)

        add_button.clicked.connect(self.add_data)
        delete_button.clicked.connect(self.delete_data)
        save_button.clicked.connect(self.save_data)

        self.account_table = QtWidgets.QTableWidget()
        self.account_table.setColumnCount(10)
        self.account_table.setHorizontalHeaderLabels(
            ["id", "账户名称", "交易账号", "交易密码", "经纪商代码", "交易服务器", "行情服务器", "产品名称",
             "授权编码", "初始本金"])

        self.account_table.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
        self.account_table.verticalHeader().setVisible(False)
        self.account_table.setMinimumWidth(1000)

        account_layout.addWidget(self.account_table)
        account_layout.addLayout(button_layout)

        self.setLayout(account_layout)
        self.load_data()

    def load_data(self):
        # 获取数据库中的账户数据 并显示在表格中
        accounts: List[AccountModelData] = self.db.load_account_data()
        self.account_table.setRowCount(len(accounts))

        for row, account in enumerate(accounts):
            item_id = QtWidgets.QTableWidgetItem(str(account.id))
            item_username = QtWidgets.QTableWidgetItem(account.username)
            item_account = QtWidgets.QTableWidgetItem(account.account)
            item_password = QtWidgets.QTableWidgetItem(account.password)
            item_broker = QtWidgets.QTableWidgetItem(account.broker)
            item_trade_server = QtWidgets.QTableWidgetItem(account.trade_server)
            item_quotation_server = QtWidgets.QTableWidgetItem(account.quotation_server)
            item_product_name = QtWidgets.QTableWidgetItem(account.product_name)
            item_authorization_code = QtWidgets.QTableWidgetItem(account.authorization_code)
            item_init_balance = QtWidgets.QTableWidgetItem(str(account.init_balance))

            self.account_table.setItem(row, 0, item_id)
            self.set_cell_editable(row, 0, False)

            self.account_table.setItem(row, 1, item_username)
            self.account_table.setItem(row, 2, item_account)
            self.account_table.setItem(row, 3, item_password)
            self.account_table.setItem(row, 4, item_broker)
            self.account_table.setItem(row, 5, item_trade_server)
            self.account_table.setItem(row, 6, item_quotation_server)
            self.account_table.setItem(row, 7, item_product_name)
            self.account_table.setItem(row, 8, item_authorization_code)
            self.account_table.setItem(row, 9, item_init_balance)

    def set_cell_editable(self, row, column, editable):
        item = self.account_table.item(row, column)
        if item:
            flags = item.flags()
            if editable:
                flags |= QtCore.Qt.ItemFlag.ItemIsEnabled
            else:
                flags &= ~QtCore.Qt.ItemFlag.ItemIsEnabled
            item.setFlags(flags)

    def add_data(self):
        row_count = self.account_table.rowCount()
        self.account_table.insertRow(row_count)

        # 选择具有最高 ID 值的账户数据
        last_account: AccountModelData = AccountModelDataTable.select().order_by(AccountModelDataTable.id.desc()).get()

        item_id = QtWidgets.QTableWidgetItem(str(last_account.id + 1))
        self.account_table.setItem(row_count, 0, item_id)

    def delete_data(self):
        current_row = self.account_table.currentRow()

        if current_row < 0:
            QMessageBox.warning(self, "删除账户", "请先选择要删除的账户")
            return
        account = self.account_table.item(current_row, 2).text()
        self.account_table.removeRow(current_row)

        res = self.db.delete_account_data(account)
        if res:
            # 弹出成功消息框
            QMessageBox.information(self, "成功", "删除账户成功！")
        else:
            QMessageBox.warning(self, "警告", "删除账户失败")

    def save_data(self) -> None:
        # 保存表格数据到数据库
        row_count = self.account_table.rowCount()
        accountDatas: List[AccountModelData] = []
        riskDatas: List[RiskManagerModelData] = []
        for row in range(row_count):
            id = self.account_table.item(row, 0).text()
            username = self.account_table.item(row, 1).text()
            account = self.account_table.item(row, 2).text()
            password = self.account_table.item(row, 3).text()
            broker = self.account_table.item(row, 4).text()
            trade_server = self.account_table.item(row, 5).text()
            quotation_server = self.account_table.item(row, 6).text()
            product_name = self.account_table.item(row, 7).text()
            authorization_code = self.account_table.item(row, 8).text()
            init_balance = self.account_table.item(row, 9).text()

            # 获取每一行的数据并保存到数据库
            accountData = AccountModelData(
                id=id,
                username=username,
                account=account,
                password=password,
                broker=int(broker),
                trade_server=trade_server,
                quotation_server=quotation_server,
                product_name=product_name,
                authorization_code=authorization_code,
                init_balance=float(init_balance)
            )
            riskData = RiskManagerModelData(
                id=id,
                username=username,
                account=account,
                max_loss=0.1,
                sleep=0
            )
            riskDatas.append(riskData)
            accountDatas.append(accountData)
        res1 = self.db.save_account_data(accountDatas)
        res2 = self.db.save_riskManager_data(riskDatas)
        if res1 and res2:
            QMessageBox.information(self, "成功", "保存成功，重启后生效！")
        else:
            QMessageBox.warning(self, "警告", "保存失败")

        # 保存完成后重新加载数据
        self.load_data()

    def closeEvent(self, event):
        # 比如保存数据或执行清理操作
        self.db.quit()
        # 调用父类的 closeEvent 方法，以确保对话框正常关闭
        super().closeEvent(event)
